<!-- 未实现账号密码加密 -->
<template>
  <div class = "login-body">
    <div class = "login-panel">
      <div class = "login-title">登陆觅心阁</div>
      <el-form :model = "formData" 
               :rules = "rules"
                ref="formDataRef" >

        <el-form-item label="" prop = "account">
          <el-input placeholder="请输入邮箱或手机号"
                    v-model="formData.account" 
                    >
            <template #prefix>
              <span class = "iconfont icon-user-filling"></span>
            </template>        
          </el-input>
        </el-form-item>

        <el-form-item label="" prop = "password">
          <el-input placeholder="请输入密码"
                    v-model="formData.password" 
                    type = "password"
                    show-password>
            <template #prefix>
              <span class = "iconfont icon-password"></span>
            </template>        
          </el-input>
        </el-form-item>

        <el-form-item class = "login-checkcode" prop = "checkCode">
          <el-input placeholder="请输入验证码"
                    v-model="formData.checkCode" 
                    >        
            <template #prefix>
              <span class = "iconfont icon-yanzhengma"></span>
            </template>  

          </el-input>
          <span style="width: 40px;"></span>
          <img class = "login-checkCode-image" :src="checkCodeUrl" @click="refreshCheckCode"/>
        </el-form-item>

        <el-form-item label="">
          <el-checkbox class = "login-checkBox" v-model="formData.rememberMe"  
                       :label = "true"> 记住密码</el-checkbox>
          <div class = "login-anotherlogin">
            <span class = "login-anotherlogin-text">其他登录方式 :</span>
            <span class = "iconfont icon-wechat"></span> 
            <span class = "iconfont icon-gitee-fill-round"></span>
            <span class = "iconfont icon-githublogo"></span>
          </div>
        </el-form-item>

        <el-form-item label="">
          <el-button class = "login-button" type = "primary"  @click = "clicked" >
            登陆
          </el-button>
        </el-form-item>

      </el-form>
    </div>

    <div class="el-login-bottom">
      <span>blog CopyRight © 2023.4 - {{ new Date().getFullYear() }}.{{ new Date().getMonth()+1 }} By 觅心阁</span>
    </div> 
  
  </div>
</template>

<script setup>
import VueCookies from 'vue-cookies'
import axios from 'axios';
import { getCurrentInstance, reactive, ref, triggerRef } from "vue"
import { useRouter } from 'vue-router';
import md5 from 'js-md5';
import JM from '../../api/MXGJM'
//import { login } from '@/api/Login'
//import { useStore } from 'vuex'

//const store = useStore()

const { proxy } = getCurrentInstance();
const router = useRouter();
// 响应式变量
const formDataRef = ref();
const formData = reactive({
    account: '',
    password: '',
    checkCode: '',
    rememberMe: true,
  });
  const loading = ref(false);

  const phoneNumpattern = /^1[3-9]\d{9}$/;
  const emailPattern = /^([a-zA-Z0-9_-]+[\.\+])*[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]{2,})+$/;
  const passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d)[\s\S]{6,16}$/;

  // refreshCheckCode函数用于刷新验证码图片
  const checkCodeUrl = ref('http://localhost:8081/api/captcha');
  const refreshCheckCode = () => {
    const timestamp = new Date().getTime();
    checkCodeUrl.value += `/?t=${timestamp}`;
  };

  const rules = {
    account: [{
      required: true,
      message: "账号不能为空！",
    },
    {
      validator: (rule, value, callback) => {
        if (!phoneNumpattern.test(value) && !emailPattern.test(value)) {
          callback(new Error("账号格式不正确，请输入正确的手机号或邮箱！"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
    password: [{
      required: true,
      message: "密码不能为空！"
    },

    ],
    checkCode: [{
    required: true,
    message: "验证码不能为空！"
    }],
  };

  // 初始化函数
  const init = () => {
    const loginInfo = VueCookies.get("loginInfo");
    if (loginInfo) {
      Object.assign(formData, loginInfo);
    }
  };
  init();

  // 点击事件函数
  const clicked = async() => {
    // 发送请求前，将 loading 设置为 true，使按钮变为“登录中”
    //loading.value = true;

    formDataRef.value.validate(async(valid) => {
      if (!valid) {
        return;
      }
      let upPassword = formData.password;
      let upCheckCode = formData.checkCode;
      let upAccount = formData.account;
      //let up = JM(upAccount, upPassword, upCheckCode);
      // console.log(up); 
      // upPassword = md5(up);
      console.log(upPassword); 
      // 发送登录请求
      const url = 'http://localhost:8081/api/login';
      const data = {
        account: formData.account,
        password: upPassword,
        checkCode: formData.checkCode,
      };

      //store.dispatch('app/login', data)

      //await login(data)

      try {
        const res = await axios.post(url, data);
        //await login(data)
        if (res.data.code == 2000) {
          // 登录成功，保存登录信息到 cookie
          if(formData.rememberMe)
          {
            VueCookies.set("loginInfo", { account: formData.account, password: formData.password, rememberMe: formData.rememberMe });
          }
          // 跳转到首页
          setTimeout(() => {
            router.push("/");
          }, 1000);
        }
        else {
          // 登录失败，提示用户
          proxy.$message.error(res.data.message);
        }
      } catch(e) {
        console.error(e);
        proxy.$message.error('登录失败，请稍后重试！');
      } finally {
        // 请求结束时，将 loading 设为 false，恢复按钮状态
        loading.value = false;     
      }
     });
};

</script>

<style lang="scss">
.login-body{
  font-family: "micrsoft yahei";
  width: 100%;
  height:calc(100vh);
  background-size: cover;
  background-image: url(../../assets/login_body.jpg);
  background-position: center;
  
  .login-panel{
    width: 36%;
    background: rgba(255, 255, 255, 0.7);
    float: right;
    //position: center;
    //text-align: center;

    padding: 20px;
    margin-right: 32%;
    margin-top: 10%;
    border-radius: 5px;
    box-shadow: 2px, 2px, 10px #fff;

    .login-checkcode{
      display: flex;
      align-items: center;
      .el-input{
        flex: 1;
      }
    }

    .login-button{
      width: 100%;
    }
   
    .login-anotherlogin{
      float: left;
      margin-left: auto;
      display: flex;
      align-items: center;
      span{
        margin-right:10px; /* 调整间距 */
      }
      span:last-child{
        margin-right: 0;
      }
    }
      
    .login-title{
      text-align: center;
      font-size: 20px;
      margin-bottom: 10px;
    }
  }

  .el-login-bottom{
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      padding: 10px;
      //background-color: #f5f5f5;
      text-align: center;
    }
}
</style>